package waskung

import (
	"encoding/json"
	"fmt"
	"strings"
)

// AlignTableColumns adds a <style> element that gives the specified alignment
// to certain columns of a table.
func (h *HTMLWriter) AlignTableColumns(tableID, alignment string, columnIndices ...int) {
	var selectors []string
	for _, col := range columnIndices {
		selectors = append(selectors, fmt.Sprintf("#%s tr :nth-child(%d)", tableID, col))
	}
	rule := fmt.Sprintf("%s { text-align: %s }", strings.Join(selectors, ", "), alignment)
	h.Tag("style").Text(rule)
}

// TableHeadings adds a <thead> element containing one row with the specified
// headings.
func (h *HTMLWriter) TableHeadings(headings ...string) {
	h.Thead().With(func() {
		h.Tr().With(func() {
			for _, heading := range headings {
				h.Th().Text(heading)
			}
		})
	})
}

// TableRow adds a <tr> element, with a <td> element for each element in cells.
func (h *HTMLWriter) TableRow(cells ...string) {
	h.Tr().With(func() {
		for _, s := range cells {
			h.Td().Text(s)
		}
	})
}

// AssignJSVariables adds a <script> element that assigns values to
// JavaScript global variables according to the keys and values in data.
func (h *HTMLWriter) AssignJSVariables(data map[string]interface{}) {
	var b []byte
	for k, v := range data {
		j, err := json.Marshal(v)
		if err != nil {
			h.Error(err)
			return
		}
		b = append(b, k...)
		b = append(b, ' ', '=', ' ')
		b = append(b, j...)
		b = append(b, ';', '\n')
	}
	h.Script(string(b))
}
